﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace SEP.Admin
{
    public partial class Reports : System.Web.UI.Page
    {
        private static string _connectionStringKey = "SEP";

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                this.BindTree();
            }
        }

        private void BindTree()
        {
            DatabaseWrapper db = new DatabaseWrapper(_connectionStringKey, "select * from REPORTINGVIEWCATALOG where PARENTID is null;", System.Data.CommandType.Text);
            
            foreach (DataRow row in db.ExecuteDataTable().Rows)
            {
                int index = 0;
                Guid id = DataAccessLogic.DataAccess.CheckForGuidColumn(row, "ID");

                trvReports.Nodes.Add(new TreeNode(DataAccessLogic.DataAccess.CheckForStringColumn(row, "FRIENDLYVIEWNAME"), id.ToString()));

                List<SqlParameter> parms = new List<SqlParameter>();
                parms.Add(new SqlParameter("@ID", id));

                db.CommandText = "select * from REPORTINGVIEWCATALOG where PARENTID = @ID;";
                db.Parameters = parms;

                foreach (DataRow child in db.ExecuteDataTable().Rows)
                {
                    id = DataAccessLogic.DataAccess.CheckForGuidColumn(child, "ID");
                    trvReports.Nodes[index].ChildNodes.Add(new TreeNode(DataAccessLogic.DataAccess.CheckForStringColumn(child, "FRIENDLYVIEWNAME"), id.ToString()));
                }

                index++;
            }
        }

        private void BindGridView(Guid id)
        {
            DatabaseWrapper db = new DatabaseWrapper(_connectionStringKey, "select * from REPORTINGVIEWCATALOG where ID = @ID;", System.Data.CommandType.Text);
            List<SqlParameter> parms = new List<SqlParameter>();
            parms.Add(new SqlParameter("@ID", id));
            db.Parameters = parms;

            DataRow row = db.ExecuteDataTable().Rows[0];            
            
            string sql = string.Concat("select * from ", row["DBVIEWNAME"].ToString());

            db.CommandText = sql;
            db.ClearParameters();
            grvReport.DataSource = db.ExecuteDataTable();
            grvReport.DataBind();
        }

        protected void trvReports_SelectedNodeChanged(object sender, EventArgs e)
        {
            Guid id = new Guid(((TreeView)sender).SelectedValue);

            BindGridView(id);
        }
    }
}